package com.talent.jiwen_teacher.receiver;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.abc.live.ABCLiveUIHelp;
import com.abc.live.OrderBean;
import com.abc.live.widget.common.ABCLiveControllerView;
import com.abcpen.core.define.ABCConstants;
import com.abcpen.open.api.model.RoomMo;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.talent.jiwen_teacher.ActivityManager;
import com.talent.jiwen_teacher.HomeFragment;
import com.talent.jiwen_teacher.IndexActivity;
import com.talent.jiwen_teacher.R;
import com.talent.jiwen_teacher.chatlive.InteractiveActivity;
import com.talent.jiwen_teacher.course.CourseFragment;
import com.talent.jiwen_teacher.course.CourseWaitFragment;
import com.talent.jiwen_teacher.course.WaitSureFragment;
import com.talent.jiwen_teacher.data.JPushCommonInfo;
import com.talent.jiwen_teacher.data.JPushExtraData;
import com.talent.jiwen_teacher.http.common.ApiFactory;
import com.talent.jiwen_teacher.http.common.HttpUtil;
import com.talent.jiwen_teacher.http.common.ProgressSubscriber;
import com.talent.jiwen_teacher.http.result.OrderResult;
import com.talent.jiwen_teacher.ui.widgets.RemindDialog;
import com.talent.jiwen_teacher.util.MaterialDialogUtil;
import com.talent.jiwen_teacher.util.SPConstant;
import com.talent.jiwen_teacher.util.SPUtil;
import com.talent.jiwen_teacher.util.Validators;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import cn.robotpen.utils.screen.LogUtils;
import rx.Observable;

import static android.content.Context.NOTIFICATION_SERVICE;
import static com.talent.jiwen_teacher.HomeFragment.RED_SHOW;
import static com.talent.jiwen_teacher.HomeFragment.REFRESH_HOME_ORDER_LIST;
import static com.talent.jiwen_teacher.my.MyFragment.REFRESH_DATA;

public class MyJPushReceiver extends BroadcastReceiver {
    private static String TAG = "MyJPushReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        //Log.d(TAG, "onReceive - " + intent.getAction());

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {

        }
        else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent
                .getAction())) {
            // 自定义消息不会展示在通知栏，完全要开发者写代码去处理
            String content = bundle.getString(JPushInterface.EXTRA_MESSAGE);
            String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);


            try {
                Gson gson = new Gson();
                JPushExtraData extraData = JSON.parseObject(extra , JPushExtraData.class);
                String extraMessage  = extraData.getExtraMessage();
                JPushCommonInfo message = gson.fromJson(extraMessage , JPushCommonInfo.class);
                int messageType = message.getMessageType();
                switch (messageType){
//                    case JPushCommonInfo.TEACHER_TIME_OVER://免单课程结束
//                        EventBus.getDefault().post(InteractiveActivity.TIME_FINISH_CLASS);
//                        EventBus.getDefault().post(CourseWaitFragment.REFRESH_WAIT_COURSE);
//                        EventBus.getDefault().post(WaitSureFragment.REFRESH_WAIT_SURE);
//                        break;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent
                .getAction())) {
            // 在这里可以做些统计，或者做些其他工作

            String extra  =bundle.getString(JPushInterface.EXTRA_EXTRA);
            LogUtils.e("收到了通知消息@@消息extra是:" + extra);

            try {
                Gson gson = new Gson();

                JPushExtraData extraData = JSON.parseObject(extra , JPushExtraData.class);
                String extraMessage  = extraData.getExtraMessage();
                JPushCommonInfo message = gson.fromJson(extraMessage , JPushCommonInfo.class);
                int messageType = message.getMessageType();
                switch (messageType){
                    case JPushCommonInfo.NOTIFY_TEACHER_ORDER:
//                        SoundHelper.get().palyOrder();
                        //学生提问，通知老师抢单
                        EventBus.getDefault().post(REFRESH_HOME_ORDER_LIST);
//                        processCustomMessage(context,bundle);

                        break;
                    case JPushCommonInfo.START_COURSE:
                        //开始上课
                        Map<String , Object> startCourseMap = message.getMessageMap();
                        Double roomId = (Double) startCourseMap.get("roomId");
//                        String questionIntroduction= (String) startCourseMap.get("questionName");
//                        String questionImages= (String) startCourseMap.get("questionImages");
                        if(roomId!=null){
                            showStartClassDialog(roomId.intValue() + "");
                            EventBus.getDefault().post(RED_SHOW);
                        }
                        break;
                    case JPushCommonInfo.STUDENT_ACCEPT_ORDER:
                        //学生接受老师
                        EventBus.getDefault().post(CourseWaitFragment.REFRESH_WAIT_COURSE);
                        EventBus.getDefault().post(WaitSureFragment.REFRESH_WAIT_SURE);
                        EventBus.getDefault().post(RED_SHOW);
                        break;
                    case JPushCommonInfo.CERT_NOTIFY://认证通知
                        Map<String , Object> msgMap = message.getMessageMap();
                        String NIToken = (String) msgMap.get("IMToken");
                        SPUtil.stringIn(SPConstant.NIM_TOKEN,NIToken);
                        EventBus.getDefault().post(REFRESH_DATA);
                        EventBus.getDefault().post(HomeFragment.REFRESH_HOME_ORDER_LIST);
                        break;

                    case JPushCommonInfo.STUDENT_LATE:
                        //学生迟到
                        break;
                    case JPushCommonInfo.TEACHER_LATE:
                        //教师迟到
                        break;
                    case JPushCommonInfo.STUDENT_CANCEL://学生取消订单
                    case JPushCommonInfo.TEACHER_CANCEL://老师取消订单
                        EventBus.getDefault().post(CourseWaitFragment.REFRESH_WAIT_COURSE);
                        EventBus.getDefault().post(WaitSureFragment.REFRESH_WAIT_SURE);
                        break;
//                    case JPushCommonInfo.TEACHER_TIME_OVER://免单课程结束
//                        EventBus.getDefault().post(InteractiveActivity.TIME_FINISH_CLASS);
//                        EventBus.getDefault().post(CourseWaitFragment.REFRESH_WAIT_COURSE);
//                        EventBus.getDefault().post(WaitSureFragment.REFRESH_WAIT_SURE);
//                        break;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent
                .getAction())) {
            String extra  =bundle.getString(JPushInterface.EXTRA_EXTRA);
            LogUtils.e("收到了通知消息@@消息extra是:" + extra);

            try {
                Gson gson = new Gson();

                JPushExtraData extraData = JSON.parseObject(extra , JPushExtraData.class);
                String extraMessage  = extraData.getExtraMessage();

                JPushCommonInfo message = gson.fromJson(extraMessage , JPushCommonInfo.class);
                int messageType = message.getMessageType();
                switch (messageType){
                    case JPushCommonInfo.NOTIFY_TEACHER_ORDER:
                        //学生提问，通知老师抢单
                        Intent orderIntent = new Intent(context, IndexActivity.class);
                        IndexActivity.tab1Checked = true;
                        orderIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(orderIntent);

                        EventBus.getDefault().post(REFRESH_HOME_ORDER_LIST);

                        break;
                    case JPushCommonInfo.START_COURSE:
                        //开始上课
//                        Intent courseIntent = new Intent(context, IndexActivity.class);
//                        IndexActivity.tab2checked = true;
//                        courseIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        context.startActivity(courseIntent);
//
//                        CourseFragment.fragment1Checked = true;
//                        EventBus.getDefault().post(CourseWaitFragment.REFRESH_WAIT_COURSE);
//                        EventBus.getDefault().post(WaitSureFragment.REFRESH_WAIT_SURE);
                        break;
                    case JPushCommonInfo.STUDENT_ACCEPT_ORDER:
                        //学生接受老师
                        Intent acceptIntent = new Intent(context, IndexActivity.class);
                        IndexActivity.tab2checked = true;
                        acceptIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(acceptIntent);

                        CourseFragment.fragment1Checked = true;
                        EventBus.getDefault().post(CourseWaitFragment.REFRESH_WAIT_COURSE);
                        EventBus.getDefault().post(WaitSureFragment.REFRESH_WAIT_SURE);
                        break;

                    case JPushCommonInfo.CERT_NOTIFY://认证通知
//                        Map<String , Object> msgMap = message.getMessageMap();
//                        String NIToken = (String) msgMap.get("IMToken");
//                        SPUtil.stringIn(SPConstant.NIM_TOKEN,NIToken);
                        Intent msgIntent = new Intent(context, IndexActivity.class);
                        IndexActivity.tab3Checked = true;
                        msgIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(msgIntent);

                        break;
                    case JPushCommonInfo.STUDENT_LATE://学生上课逾期通知
                    case JPushCommonInfo.TEACHER_LATE://教师上课逾期通知
                    case JPushCommonInfo.STUDENT_CANCEL://学生取消订单，已确认
                    case JPushCommonInfo.TEACHER_CANCEL://老师取消订单

                        Intent courseIntent = new Intent(context, IndexActivity.class);
                        IndexActivity.tab2checked = true;
                        courseIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(courseIntent);

                        CourseFragment.fragment1Checked = true;
                        EventBus.getDefault().post(CourseWaitFragment.REFRESH_WAIT_COURSE);
                        EventBus.getDefault().post(WaitSureFragment.REFRESH_WAIT_SURE);
                        break;
                    default:
                        //默认直接打开应用
                        Intent defaultIntent = new Intent(context, IndexActivity.class);
                        defaultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(defaultIntent);
                        break;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        else {
            //Log.d(TAG, "Unhandled intent - " + intent.getAction());
        }
    }


    private static final int NOTIFICATION_SHOW_SHOW_AT_MOST = 3;   //推送通知最多显示条数

    /**
     * 实现自定义推送声音
     * @param context
     * @param bundle
     */
    private void processCustomMessage(Context context, Bundle bundle) {
        NotificationCompat.Builder notification = new NotificationCompat.Builder(context);

        String title = bundle.getString(JPushInterface.EXTRA_TITLE);
        String msg = bundle.getString(JPushInterface.EXTRA_MESSAGE);
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);

        Intent mIntent = new Intent(context,IndexActivity.class);
        IndexActivity.tab1Checked = true;
        mIntent.putExtras(bundle);
        mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, mIntent, 0);

        notification.setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .setContentText(msg)
                .setContentTitle(title.equals("") ? "title": title)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(bitmap)
                .setNumber(NOTIFICATION_SHOW_SHOW_AT_MOST);

        Log.e(TAG, "processCustomMessage: extras----->" + extras);
        if (!TextUtils.isEmpty(extras)) {
            try {
                JSONObject extraJson = new JSONObject(extras);
                if (null != extraJson && extraJson.length() > 0) {
                    String sound = extraJson.getString("sound");
                    if("1".equals(sound)){
                        notification.setSound(Uri.parse("android.resource://" + context.getPackageName() + "/" +R.raw.xdd));
                    } else {
                        notification.setSound(Uri.parse("android.resource://" + context.getPackageName() + "/" +R.raw.xdd));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_SHOW_SHOW_AT_MOST, notification.build());  //id随意，正好使用定义的常量做id，0除外，0为默认的Notification
    }


    /**显示上课Dialog
     *
     * @param roomId
     */
    private void showStartClassDialog(final String roomId){
        if(!Validators.isEmpty(SPUtil.getUserId())){
            Activity activity = ActivityManager.getAppManager().currentActivity();
            if (null != activity){
                RemindDialog dialog = MaterialDialogUtil.getOneOptionRemindDialog(activity, R.mipmap.dialog_start_course ,"您的课程已经开始啦！"
                        , "立即进入", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                startClass(roomId);
                            }
                        });
                dialog.show();
            }
        }
    }


    int count=0;

    /**
     * 老师开始上课
     */
    private void startClass(final String orderId){

        Activity activity = ActivityManager.getAppManager().currentActivity();
        Map<String, String> map = new HashMap<>();
        map.put("teacherId", SPUtil.stringOut(SPConstant.USER_ID));
        map.put("orderId", orderId);

        Observable observable = ApiFactory.getEducationApiSingleton().teacherStartClass(SPUtil.stringOut(SPConstant.TOKEN), map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<OrderResult>(activity) {
            @Override
            protected void _onNext(OrderResult orderResult) {
                if(orderResult!=null){
                    ABCLiveControllerView.isHiddenController=false;
                    goLive(orderId,new OrderBean(orderResult.questionName,orderResult.questionImages,orderResult.orderType));
                }
            }

            @Override
            protected void _onError(String message) {
                count++;
                if(count<5){
                    startClass(orderId);
                }else{
                    count=0;
                }
            }
        } , true);
    }



    public void goLive(String roomId,OrderBean orderBean) {
        String rid = roomId;
        int liveType = 2;
        ABCLiveUIHelp uiHelp = ABCLiveUIHelp.init()
                .setUserID(SPUtil.getBSUId())
                .setUserName(SPUtil.getUserName())
                .setIsManager(false)
                .setDefaultOpenCamera(false)
                .setDefaultOpenMic(true);

        RoomMo roomMo = new RoomMo();
        roomMo.room_id = rid;
        roomMo.name = rid;
        roomMo.live_type = liveType;
        ABCLiveUIHelp abcLiveUIHelp = null;
        if(!SPUtil.booleanDataOut(SPConstant.IS_FIRST_GUIDE)){
            abcLiveUIHelp= uiHelp.setIsShowGuide(true);
            SPUtil.booleanDataIn(SPConstant.IS_FIRST_GUIDE,true);
        }else{
            abcLiveUIHelp= uiHelp.setIsShowGuide(false);
        }
        abcLiveUIHelp.setIsManager(false);
        roomMo.isRecord =1 ;//isRecording ? 1 : 2
        abcLiveUIHelp.setUserIconDefault(R.drawable.abc_default_icon);
        abcLiveUIHelp.setUserAvatarUrl(SPUtil.getUserHeadImg());
//        abcLiveUIHelp.setEndTime(System.currentTimeMillis() + 45 * 1000);
        abcLiveUIHelp.setStartTime(System.currentTimeMillis() + 10 * 1000);
        abcLiveUIHelp.setRoleType(ABCConstants.HOST_TYPE);
        Activity activity = ActivityManager.getAppManager().currentActivity();
        abcLiveUIHelp.startInteractiveLiveActivity(activity, roomMo, InteractiveActivity.class,orderBean);
    }
}
